/*
 * BootLoader.h
 *
 *  Created on: Sep 9, 2021
 *      Author: ZhangJianCe
 */

#ifndef BOOTLOADER_H_
#define BOOTLOADER_H_
#include "usart.h"
#include "stm32f1xx_hal_flash_ex.h"
#include "stm32f1xx_hal_flash.h"


/*芯片Flash大小*/
#define Flash_Size (0x10000U)
#define Flash_Max_Address (0x08000000+Flash_Size-1)

#ifdef STM32F103xB
/*定义页地址无效位数量*/
#define Invalid_Bits (10)
#endif
#ifdef STM32F103xE
/*定义页地址无效位数量*/
#define Invalid_Bits (11)
#endif


/*APP中断向量表地址*/
#define APP_Address 0x8003800U

/*APP有效标志位地址，标志位长度为4*/
#define APP_Valid_Flag_Address (0x08000000+Flash_Size-4)

/*APP有效标志位*/
#define APPLICATION_VALID 0xFAAF5AA5U

/*写Flash数据块长度定义*/
#define WRITE_FLASH_BLOCKSIZE 1024

/*芯片Flash大小定义，注意每个芯片不一样，
 * 需要根据使用的芯片查看手册*/


/*程序跳转函数指针定义*/
typedef void(*JumpApp_Handle)(void);

/*BootLoader命令定义*/
#define  READ_VERSION   0xF0
#define  ERASE_FLASH    0xF1
#define  WRITE_FLASH    0xF2
#define  CALC_CHECKSUM  0xF3
#define  Jump_APP   0xF4

/*命令反馈定义*/
#define ERASE_FAILD   0xFC
#define WRITE_FAILD   0xFD
#define ERROR_ADDRESS_OUT_OF_RANGE   0xFE
#define ERROR_INVALID_COMMAND        0xFF
#define COMMAND_SUCCESS              0x01

/*BootLoader帧格式定义*/
typedef union
{
    struct
    {
        uint8_t    command;
        uint32_t   data_length;
        uint8_t    address_0;
        uint8_t    address_1;
        uint8_t    address_2;
        uint8_t    address_3;
        uint8_t    data[WRITE_FLASH_BLOCKSIZE];
    }__attribute__((packed));
    uint8_t  buffer[WRITE_FLASH_BLOCKSIZE+9];
}frame_t;

extern frame_t frame;
extern uint8_t BootLoad_Suuccess;

void Jump_Application(void);
void BootLoader_Initialize(void);
uint8_t Bootload_Required(void);
void Run_Bootloader(void);
uint8_t ProcessBootBuffer(void);
uint8_t Get_Version_Data(void);
uint8_t Write_Flash(void);
uint8_t Erase_Flash(void);
uint8_t Calc_Checksum();
void Write_APP_Valid_Flag(void);

#endif /* BOOTLOADER_H_ */
